import React from 'react';
import { Badge, Button, Dropdown } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import hljs from 'utils/hl.js';
import LineInfo from 'pages/index/pages/project/pages/projectMergeRequestDetail/pages/changes/containers/components/commentMedia/lineInfo';
import { filterXSS } from 'xss';
import { PROJECT_VIEW_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import utils from 'utils';
import track from 'utils/track';

import './index.scss';
import MarkdownIt from 'markdown-it';
import intl from '../../../../../../../../../locale';

const md = new MarkdownIt({
  highlight(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value;
      } catch (__) {
        return '';
      }
    }

    return ''; // 使用额外的默认转义
  },
});

const { pathResource } = window.FORCE;

export default class CommentList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dropdownVisible: false,
    };
  }

  closeDropdown = () => {
    this.setState({
      dropdownVisible: false,
    });
  };

  renderDraftComments = () => {
    const { drafts } = this.props.changesReducer;
    const { issueDetailList } = this.props;
    return (
      <div className="draft-comment-list">
        {drafts.map((item) => {
          if (item.issue_id) {
            const curIssue =
              issueDetailList.find((issue) => {
                return issue.id === item.issue_id;
              }) || {};
            item.line = curIssue.begin_line;
            item.side = 'right';
            item.outdated = curIssue.status && curIssue.status.toLowerCase() === 'resolved';
            item.path = curIssue.file_name;
          }
          return (
            <div className="draft-comment-list-item">
              <div className="draft-comment-list-item-left">
                <YunxiaoIcon type="log-line" />
              </div>
              <div className="draft-comment-list-item-right">
                <div className="line-info">
                  <LineInfo comment={item} maxWidth="190px" closeDropdown={this.closeDropdown} />
                </div>
                <div
                  className="content-info markdown-body"
                  dangerouslySetInnerHTML={{
                    __html: filterXSS(md.render(item.note || ''), {
                      onIgnoreTagAttr: (_, name, value) => {
                        return `${name}=${value}`;
                      },
                    }),
                  }}
                />
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  renderBtn = () => {
    const { changesReducer, mrCommentConfig, codeReviewDetail } = this.props;
    const { allComments = [] } = changesReducer;
    const hasPermission =
      pathResource.isArchive === 'false' &&
      utils.allowComments(allComments.length, mrCommentConfig);
    return (
      <div className="draft-btn-wrapper">
        <Button
          type="primary"
          className="draft-btn"
          disabled={!hasPermission}
          onClick={() => {
            if (!hasPermission) {
              return;
            }
            this.props.postDrafts('', () => {
              this.setState({
                dropdownVisible: false,
              });
            });
            track({
              action: 'push_draft',
              page: ':Repo-MR',
              type: '',
              mr_id: codeReviewDetail.id,
            });
          }}
        >
          {intl.get({
            id: 'code-assets.components.draftBtn.SubmitDraft',
            defaultMessage: '提交草稿',
          })}
        </Button>
      </div>
    );
  };

  render() {
    const { drafts } = this.props.changesReducer;
    const { role } = window.FORCE.pathResource;
    if (!drafts.length) {
      return null;
    }

    // 浏览者微调样式
    const isViewer = access(PROJECT_VIEW_ROLES, role);

    return (
      <Dropdown
        trigger={
          <div
            className="drafts-trigger"
            style={{ marginRight: isViewer ? 0 : '-12px', marginLeft: 24 }}
          >
            <Button type="normal">
              {intl.get({
                id: 'code-assets.components.draftBtn.SubmitDraft',
                defaultMessage: '提交草稿',
              })}
            </Button>
            <Badge count={drafts.length} className="drafts-num-badge" />
          </div>
        }
        triggerType="hover"
        align="tr br"
        visible={this.state.dropdownVisible}
        onVisibleChange={(dropdownVisible) => {
          this.setState({
            dropdownVisible,
          });
        }}
      >
        <div className="drafts-pop-container overlay-shadow">
          {this.renderDraftComments()}
          {this.renderBtn()}
        </div>
      </Dropdown>
    );
  }
}
